#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =================================================
# @File    : json_driver
# @IDE     : PyCharm
# @Author  : Liu Xian Gui
# @Date    : 2024/3/16 14:00
# @Describe: 
# ==================================================
import re
import json
from jsonpath import jsonpath
from typing import Union, Any


class JsonDriver:
    @classmethod
    def json_pretty_print(cls, json_data):
        """
        解决json中文输出问题
        :param json_data:
        :return:
        """
        try:
            beauty_print = json.dumps(json_data, ensure_ascii=False, indent=2)
            return beauty_print
        except:
            return json_data

    @classmethod
    def update_all_value_in_json(cls, json_object, field_to_update, new_value):
        """
        递归地更新JSON对象中所有子层级的指定字段值。
        :param json_object: JSON对象（可以是字典或列表）
        :param field_to_update: 要更新的字段名
        :param new_value: 新值
        """
        if isinstance(json_object, dict):
            # 遍历字典的键值对
            for key, value in json_object.items():
                # 如果键匹配，更新值
                if key == field_to_update:
                    json_object[key] = new_value
                    # 如果值是字典或列表，递归调用该函数
                elif isinstance(value, (dict, list)):
                    cls.update_all_value_in_json(value, field_to_update, new_value)
        elif isinstance(json_object, list):
            # 遍历列表中的每个元素
            for item in json_object:
                # 递归调用该函数
                cls.update_all_value_in_json(item, field_to_update, new_value)

    @classmethod
    def update_value_by_jsonpath(cls, json_object: Union[dict, list], path: str, new_value: Any):
        """
        根据path路径修改字段值
        :param json_object: json（可以是字典或列表）
        :param path: jsonpath路径
        :param new_value: 新值
        :return:
        """
        json_path_parent = '.'.join(path.split(".")[:-1])
        field_to_update = path.split('.')[-1]
        if json_path_parent == "$":
            json_object[field_to_update] = new_value
        else:
            cls.update_all_value_in_json(jsonpath(json_object, json_path_parent), field_to_update, new_value)

    @classmethod
    def find_jsonpath_by_value(cls, obj: Union[list, dict], target_value, path=''):
        """
        通过值，查找jsonpath
        :param obj: JSON对象（可以是字典或列表）
        :param target_value: 目标值
        :param path: jsonpath路径
        :return:
        """
        if isinstance(obj, dict):
            for key, value in obj.items():
                new_path = f'{path}.{key}' if path else key
                if value == target_value:
                    yield new_path
                if isinstance(value, (dict, list)):
                    yield from cls.find_jsonpath_by_value(value, target_value, new_path)
        elif isinstance(obj, list):
            for index, item in enumerate(obj):
                new_path = f'{path}[{index}]' if path else f'[{index}]'
                if item == target_value:
                    yield new_path
                if isinstance(item, (dict, list)):
                    yield from cls.find_jsonpath_by_value(item, target_value, new_path)

    @classmethod
    def find_json_variables(cls, json_object: str):
        return re.findall("\$\((.*?)\)", json_object)
